﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XStudio.XCRF.Data.Entities;
using XStudio.XCRF.Data.Business.Permissions;
using XStudio.XCRF.Data.Business;
using XStudio.XCRF.Data.Enums;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using XStudio.XCRF.Web.Common.Sessions;
using Telerik.Web.Mvc;
using XStudio.XCRF.Web.Models.Hospital;

namespace XStudio.XCRF.Web.Controllers
{
    /// <summary>
    /// 医院控制器
    /// </summary>
    public partial class HospitalController : BaseController
    {
        /// <summary>
        /// 处理查看医院详情的页面请求
        /// </summary>
        /// <param name="hospitalID">医院ID</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult HospitalDetail(Guid? hospitalID)
        {
            if (hospitalID == null)
                hospitalID = HospitalID;
            Hospital hospital = DataContext.Hospitals.Find(hospitalID);
            DataContext.Entry<Hospital>(hospital).Collection<Member>(h => h.Members)
                .Query().GetMasterRecords().Load();
            return View(hospital);
        }

        /// <summary>
        /// 处理编辑医院页面请求
        /// </summary>
        /// <param name="hospitalID">医院ID</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        [DenyMemberType(MemberTypes.Researcher)]
        public ActionResult HospitalEdit(Guid? hospitalID)
        {
            if (hospitalID == null)
                hospitalID = HospitalID;
            Hospital hospital = DataContext.Hospitals.Find(hospitalID);
            return View(hospital);
        }
        /// <summary>
        /// 处理编辑医院POST请求
        /// </summary>
        /// <param name="hospital">欲编辑的医院</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        [DenyMemberType(MemberTypes.Researcher)]
        [HttpPost]
        public JsonResult HospitalEdit(Hospital hospital)
        {
            try
            {
                Hospital hospital_db = DataContext.Hospitals.Find(hospital.ID);
                hospital_db.Name = hospital.Name;
                hospital_db.Address = hospital.Address;
                hospital_db.Phone = hospital.Phone;
                hospital_db.Email = hospital.Email;
                hospital_db.Website = hospital.Website;
                hospital_db.Detail = hospital.Detail;
                DataContext.SaveChanges();
                if (hospital_db.ID == HospitalID)
                {
                    Member member = DataContext.Members.Find((Guid)LoginID);
                    LoginSession.LogOut();
                    LoginSession.LogIn(member);
                    
                }
                //return Json(hospital_db);
                return Json(new { ID = hospital_db.ID });
            }
            catch
            {
                return Json(null);
            }
        }

        /// <summary>
        /// 处理添加医院页面请求
        /// </summary>
        /// <returns></returns>
        [AllowMemberType(MemberTypes.Administrator)]
        public ActionResult HospitalAdd()
        {
            Hospital hospital = new Hospital();
            return View(hospital);
        }

        /// <summary>
        /// 处理添加医院POST请求
        /// </summary>
        /// <param name="hospital"></param>
        /// <returns></returns>
        [AllowMemberType(MemberTypes.Administrator)]
        [HttpPost]
        public JsonResult HospitalAdd(Hospital hospital)
        {
            try
            {
                String sCode = DataContext.Hospitals.Max(c => c.Code);
                int code = Convert.ToInt32("1" + sCode);
                code++;
                sCode = code.ToString().Substring(1, code.ToString().Length - 1);
                hospital.Code= sCode;
                Member owner = hospital.Members.First();
                owner.RealName = "未命名用户";
                owner.Type = (byte)MemberTypes.Owner;
                DataContext.Hospitals.Add(hospital);
                DataContext.SaveChanges();
                return Json(new { ID = hospital.ID });
            }
            catch//(Exception e)
            {
                return Json(null);
            }
        }

        /// <summary>
        /// 测试医院代码是否已存在
        /// </summary>
        /// <param name="code">医院代码</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult HospitalCodeTest(string code)
        {
            bool exist = DataContext.Hospitals.Exist(code);
            var result = new { exist = exist };
            return Json(result);
        }

        [DefaultPermission(PermissionType.Allow)]
        public ActionResult HospitalList()
        {
            return View();
        }

        [DefaultPermission(PermissionType.Allow)]
        //[GridAction(EnableCustomBinding = true)]
        [GridAction]
        [HttpPost]
        public ActionResult _HospitalList()
        {
            IEnumerable<HospitalListModel> dtos = ((IQueryable<Hospital>)DataContext.Hospitals)
                .Include(h => h.Members).Include(h => h.CRFs)
                .GetMasterRecords().ToList()
                .Select(h => new HospitalListModel
                {
                    ID = h.ID,
                    Code = h.Code,
                    Name = h.Name,
                    Owner = new Member
                    {
                        ID = h.Owner.ID,
                        RealName = h.Owner.RealName
                    },
                    CRFCount = h.CRFs.GetMasterRecords().Count()
                });
            return Json(new GridModel(dtos));
        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        [HttpPost]
        public ActionResult _HospitalDelete(Hospital hospital)
        {
            if (HospitalID == hospital.ID)
                throw new Exception("不能删除自己的医院");
            Hospital hospital_db = ((IQueryable<Hospital>)DataContext.Hospitals)
                .Find(hospital.ID);
            if (hospital_db.IsHost)
                throw new Exception("不能删除核心医院");
            DataContext.Hospitals.Remove(hospital_db);
            DataContext.SaveChanges();
            return _HospitalList();
        }
        //TODO: 医院控制器待完成
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult HospitalMemberManage(Guid? hospitalID)
        {
            if (hospitalID == null)
                hospitalID = HospitalID;
            Hospital hospital = ((IQueryable<Hospital>)DataContext.Hospitals)
                .Find((Guid)hospitalID);
            return View(hospital);
        }
        [DefaultPermission(PermissionType.Allow)]
        //[GridAction(EnableCustomBinding = true)]
        [GridAction]
        public ActionResult _HospitalMemberManage(Guid? hospitalID)
        {
            List<Member> members = ((IQueryable<Member>)DataContext.Members)
                .Find(m => m.HospitalID == hospitalID).ToList();
            List<Member> dtos = (from member in members
                                 select new Member
                                 {
                                     ID = member.ID,
                                     LoginName = member.LoginName,
                                     RealName = member.RealName,
                                     Gender = member.Gender,
                                     Type = member.Type
                                 }).ToList();
            GridModel<Member> data = new GridModel<Member>(dtos);
            return Json(data);
        }
    }
}
